package com.gomyb.common.page;

import org.apache.commons.lang3.StringUtils;

import java.util.Map;

/**
 * sql条件自动装载
 */
public class SQLCondition {


    /**
     * 基于分页对象 data 属性，data属性值必须为对象属性名
     * 仅支持单方向条件
     * 多方向条件需要自己拼写sql
     *
     * @param alias sql中条件对象的别名
     */
    public static String addCondition(String sql, PageParam pageParam, String alias) {
        Map<String, String> data = pageParam.getData();
        StringBuilder csql = new StringBuilder(sql);
        if (data.size() > 0) {
            String an = "";
            if (StringUtils.isNotEmpty(alias)) {
                an = alias + ".";
            }
            for (Map.Entry<String, String> entry : data.entrySet()) {
                String key = entry.getKey();
                int idx = key.indexOf("_");
                if (-1 == idx) {
                    csql.append(" AND ").append(an).append(key).append(" = ").append(entry.getValue());
                } else {
                    String column = key.substring(0, idx);
                    int checkIdx = column.indexOf("_");
                    if (-1 != checkIdx) {
                        while (true) {
                            checkIdx = column.indexOf("_");
                            if (-1 == checkIdx) {
                                break;
                            }
                            column = key.substring(0, checkIdx);
                        }
                    }
                    String condition = key.substring(idx + 1).toUpperCase();
                    switch (condition) {
                        case "EQ":
                            csql.append(" AND ").append(an).append(column).append(" = ").append(entry.getValue());
                            break;
                        case "NOEQ":
                            csql.append(" AND ").append(an).append(column).append(" != ").append(entry.getValue());
                            break;
                        case "LIKE":
                            csql.append(" AND ").append(an).append(column).append(" LIKE ").append("'%").append(entry.getValue()).append("%'");
                            break;
                        default:
                            System.out.println("cannot find condition...");
                            csql.append(" AND ").append(an).append(key).append(" = ").append(entry.getValue());
                    }
                }
            }
        }
        return csql.toString();
    }
}
